package br.com.searchpeople.fragment;

import br.com.searchpeople.R;
import br.com.searchpeople.activity.LoginActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceClickListener;
import android.preference.PreferenceFragment;
import android.util.Log;

public class SettingsFragment extends PreferenceFragment {
	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// Load the preferences from an XML resource
		addPreferencesFromResource(R.xml.settings);
		Preference myPref = findPreference("logout");
		myPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
			@Override
			public boolean onPreferenceClick(Preference preference) {
				logoutMethod();
				return false;
			}
		});
	}

	private void logoutMethod() {

		// 1. Instantiate an AlertDialog.Builder with its constructor
		AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());

		// 2. Chain together various setter methods to set the dialog
		// characteristics
		builder.setMessage(R.string.dialog_message).setTitle(R.string.dialog_title);
		
		builder.setIcon(R.drawable.logout_icon);

		final Activity currentActivity = this.getActivity();
		builder.setPositiveButton(R.string.sair, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						SharedPreferences settings = currentActivity.getSharedPreferences("general", Context.MODE_PRIVATE);
						SharedPreferences.Editor editor = settings.edit();
						try {
							editor.clear();
						} catch (Exception e) {
							Log.e("Erron in clear sharedopreferences",e.toString());
						} finally {
							editor.commit();
						}
						Intent i = new Intent(currentActivity.getApplicationContext(), LoginActivity.class);
						startActivity(i);
						currentActivity.finish();
					}
				});
		builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						// User cancelled the dialog
					}
				});

		// 3. Get the AlertDialog from create()
		AlertDialog dialog = builder.create();
		dialog.show();

	}
}
